package com.hmjk.health.home;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.util.OnFragmentEventCallback;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Window;

public class SignInActivity extends FragmentActivity implements OnFragmentEventCallback{
	public static final String ACT_SWITCH_TO_SIGNUP = "ACT_SWITCH_TO_SIGNUP";
	public static final String ACT_SWITCH_TO_RETRIEVEPSW = "ACT_SWITCH_TO_RETRIEVEPSW";
	public static final String ACT_BACK_TO_SIGNIN = "ACT_BACK_TO_SIGNIN";
	public static final String ACT_SHOW_AGREEMENT = "ACT_SHOW_AGREEMENT";
	
	private HealthApp mApp = null;
	private FragmentManager mFm = null;
	private SignInFragment mFragSignIn = null;
	private SignUpFragment mFragSignUp = null;
	private RetrievePswFragment mFragRetrievePsw = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		setContentView(R.layout.signin_activity);
		
		mFm = getSupportFragmentManager();
		
		mFragSignIn = new SignInFragment();  
		mFragSignUp = new SignUpFragment();
		mFragRetrievePsw = new RetrievePswFragment();
		
		FragmentTransaction ft = mFm.beginTransaction();
		ft.add(R.id.container, mFragSignIn, "SIGN_IN");
		ft.commitAllowingStateLoss(); 
		
	}
	
	@Override
	public void onResume(){
		super.onResume();
		mApp.checkNetwork();
	}

	@Override
	public void onEvent(String event, Object data) {
		if(ACT_SWITCH_TO_SIGNUP.equals(event)){
			FragmentTransaction ft = mFm.beginTransaction();
			
			ft.setCustomAnimations(R.anim.r_to_l_in, R.anim.r_to_l_out, R.anim.l_to_r_in, R.anim.l_to_r_out);
			//ft.hide(mFragSignIn);
			ft.replace(R.id.container, mFragSignUp, "SIGN_UP");
			ft.addToBackStack(null);
			ft.commitAllowingStateLoss();  
		}else if(ACT_SWITCH_TO_RETRIEVEPSW.equals(event)){
			FragmentTransaction ft = mFm.beginTransaction();
			
			ft.setCustomAnimations(R.anim.r_to_l_in, R.anim.r_to_l_out, R.anim.l_to_r_in, R.anim.l_to_r_out);
			//ft.hide(mFragSignIn);
			ft.replace(R.id.container, mFragRetrievePsw, "RETRIEVE_PSW");
			ft.addToBackStack(null);
			ft.commitAllowingStateLoss();  	
		}else if(ACT_BACK_TO_SIGNIN.equals(event)){
			mFm.popBackStack();
			if(data != null){
				String user = (String) data;
				mFragSignIn.updateUser(user);
			}
		}else if(ACT_SHOW_AGREEMENT.equals(event)){
			Intent i = new Intent(this,AgreementActivity.class);
			startActivity(i);
		}
	}

}
